import {
	EditFormActionType,
	ICtrlActionResult,
	IOptViewAbility,
	IOptViewControllerParams,
	IParam,
	IViewActionResult,
	OptViewActionType,
} from '@/core/interface';
import { IOptViewController } from '@/core/interface/view/controller';
import { IOptViewStore } from '@/core/interface/view/store';
import { IEditFormAbility } from '@/core/interface/widgets/ability';
import { AuthUtil } from '@/core/utils';
import { DEViewController } from './de-view-controller';

/**
 * 选项操作视图
 *
 * @export
 * @class OptViewController
 * @extends {(DEViewController< OptViewActionType, IOptViewStore, IOptViewAbility>)}
 * @implements {IOptViewController}
 * @template T
 */
export class OptViewController
	extends DEViewController<OptViewActionType, IOptViewStore, IOptViewAbility>
	implements IOptViewController<IOptViewStore, IOptViewAbility>
{
	/**
	 * 处理视图初始化
	 *
	 * @protected
	 * @param {IOptViewControllerParams<OptViewActionType, IOptViewAbility>} params
	 * @memberof OptViewController
	 */
	protected processViewInit(
		params: IOptViewControllerParams<OptViewActionType, IOptViewAbility>
	) {
		super.processViewInit(params);
		Object.assign(this.store, { dataInfo: '' });
	}

	/**
	 * 获取表单能力
	 *
	 * @protected
	 * @return {*}  {(IEditFormAbility | undefined)}
	 * @memberof OptViewController
	 */
	protected getFormAbility(): IEditFormAbility | undefined {
		const form = this.model.ctrls.find(
			(ctrl: IParam) => ctrl.controlType === 'FORM'
		);
		if (form) {
			return this.getSubAbility<IEditFormAbility>(form.name);
		}
		return undefined;
	}

	/**
	 * 视图加载
	 *
	 * @param {IParam} [opts={}]
	 * @return {*}
	 * @memberof OptViewController
	 */
	public viewMounted(opts: IParam = {}) {
		super.viewMounted(opts);
		if (this.model.useDefaultLayout) {
			if (!this.isLoadDefault) {
				this.isLoadDefault = true;
				return;
			}
			this.load();
		} else {
			this.initLayout().then(() => {
				this.load();
			});
		}
	}

	/**
	 * 加载
	 *
	 * @param {IParam} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof OptViewController
	 */
	public load(args?: IParam): Promise<IViewActionResult> {
		const form = this.getFormAbility();
		if (form) {
			let action: 'loadDraft' | 'load' = 'loadDraft';
			if (
				this.model.entityCodeName &&
				this.store.context[this.model.entityCodeName.toLowerCase()]
			) {
				action = 'load';
			}
			return form[action](this.store.viewParams);
		}
		return Promise.reject({ ok: false, data: null, rowData: { status: 500 } });
	}

	/**
	 * 处理编辑表单行为
	 *
	 * @param {string} name 表单标识
	 * @param {FormActionType} action 表单行为
	 * @param {IParam[]} data 行为数据
	 * @memberof EditViewController
	 */
	public handleCtrlAction(
		name: string,
		action: EditFormActionType,
		data: IParam[]
	): void {
		super.handleCtrlAction(name, action, data);
		if (action === 'load' || action === 'loadDraft') {
			this.handleFormLoad(data);
		}
		if (action === 'save') {
			this.handleFormSave(data);
		}
		if (action === 'remove') {
			this.handleFormRemove(data);
		}
	}

	/**
	 * 处理表单加载完成
	 *
	 * @param {IParam[]} data 表单数据
	 * @memberof EditViewController
	 */
	protected async handleFormLoad(data: IParam[]) {
		await this.handleFormData(data);
		this.emit('viewDataLoaded', data);
	}

	/**
	 * 处理表单保存
	 *
	 * @param {IParam[]} data
	 * @memberof EditViewController
	 */
	protected async handleFormSave(data: IParam[]) {
		await this.handleFormData(data);
		this.emit('viewDataChange', data);
		this.emit('viewDataSave', data);
	}

	/**
	 * 处理表单删除
	 *
	 * @param {IParam[]} data
	 * @memberof EditViewController
	 */
	protected handleFormRemove(data: IParam[]) {
		this.emit('viewDataChange', data);
	}

	/**
	 * 处理表单数据
	 *
	 * @param {IParam[]} data
	 * @memberof EditViewController
	 */
	protected async handleFormData(data: IParam[]) {
		const arg = data[0];
		this.store.dataInfo = Object.is(arg.srfuf, '1')
			? this.model.majorPSAppDEField
				? arg[this.model.majorPSAppDEField.toLowerCase()]
				: arg.srfmajortext
			: '新建';
		AuthUtil.calcToolbarItemState(
			Object.is(arg.srfuf, '0'),
			this.store.toolbarCtrls
		);
		await this.calcToolbarItemAuthState(arg);
	}

	/**
	 * 确认
	 *
	 * @memberof OptViewController
	 */
	public confirm() {
		const form = this.getFormAbility();
		if (form) {
			form
				.save()
				.then((response: ICtrlActionResult) => {
					if (response.ok) {
						this.emit('viewClose', response.data ? response.data : []);
					}
				})
				.catch((error: any) => {
					console.error(error);
				});
		}
	}

	/**
	 * 取消
	 *
	 * @memberof OptViewController
	 */
	public cancel() {
		this.emit('viewClose', []);
	}
}
